{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Code generation, optimization and debugging\n",
    "\n",
    "This snippets are used as prompts for ChatGPT"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<map object at 0x00000296658C80D0>\n",
      "0:00:00.000286\n"
     ]
    }
   ],
   "source": [
    "from timeit import default_timer as timer\n",
    "from datetime import timedelta\n",
    "\n",
    "start = timer()\n",
    "\n",
    "s = 'chatgpt'\n",
    "\n",
    "U = map(str.upper, s) \n",
    "print (U)\n",
    "\n",
    "end = timer()\n",
    "print(timedelta(seconds=end-start))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<map object at 0x00000296658C80D0>\n",
      "0:00:00.000286\n"
     ]
    }
   ],
   "source": [
    "from timeit import default_timer as timer\n",
    "from datetime import timedelta\n",
    "\n",
    "start = timer()\n",
    "\n",
    "s = 'chatgpt'\n",
    "\n",
    "U = map(str.upper, s) \n",
    "print (U)\n",
    "\n",
    "end = timer()\n",
    "print(timedelta(seconds=end-start))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0:00:00.141185\n",
      "0:00:00.073695\n"
     ]
    }
   ],
   "source": [
    "from timeit import default_timer as timer\n",
    "from datetime import timedelta\n",
    "\n",
    "start = timer()\n",
    "\n",
    "#my script\n",
    "elements = list(range(1_000_000))\n",
    "data = []\n",
    "for el in elements:\n",
    "      if el % 2 != 0:\n",
    "        data.append(el)\n",
    "\n",
    "end = timer()\n",
    "print(timedelta(seconds=end-start))\n",
    "\n",
    "start = timer()\n",
    "\n",
    "#ChatGPT generated script\n",
    "elements = list(range(1_000_000))\n",
    "data = [el for el in elements if el % 2 != 0]\n",
    "\n",
    "end = timer()\n",
    "print(timedelta(seconds=end-start))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "47.802528597230584"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "start_time = datetime.strptime('0:00:00.141185', '%H:%M:%S.%f')\n",
    "end_time = datetime.strptime('0:00:00.073695', '%H:%M:%S.%f')\n",
    "difference = start_time - end_time\n",
    "percentage_reduction = difference / timedelta(seconds=0.141185) * 100\n",
    "\n",
    "percentage_reduction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "t_\n"
     ]
    }
   ],
   "source": [
    "def add_underscores(word):\n",
    "    new_word = \"_\"\n",
    "    for i in range(len(word)):\n",
    "        new_word = word[i] + \"_\"\n",
    "    return new_word\n",
    "\n",
    "phrase = \"gpt\"\n",
    "print(add_underscores(phrase))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "g_p_t_\n"
     ]
    }
   ],
   "source": [
    "def add_underscores(word):\n",
    "    new_word = \"\"\n",
    "    for i in range(len(word)):\n",
    "        new_word += word[i] + \"_\"\n",
    "    return new_word\n",
    "\n",
    "phrase = \"gpt\"\n",
    "print(add_underscores(phrase))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Documentation generation and code explainability\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Calculator:\n",
    "    \n",
    "    def add(self, x, y):\n",
    "        return x + y\n",
    "    \n",
    "    def subtract(self, x, y):\n",
    "        return x - y\n",
    "    \n",
    "    def multiply(self, x, y):\n",
    "        return x * y\n",
    "    \n",
    "    def divide(self, x, y):\n",
    "        try:\n",
    "            return x / y\n",
    "        except ZeroDivisionError:\n",
    "            print(\"Error: division by zero\")\n",
    "            return None\n",
    "    \n",
    "    def power(self, x, y):\n",
    "        return x ** y\n",
    "    \n",
    "    def square_root(self, x):\n",
    "        try:\n",
    "            return x ** 0.5\n",
    "        except ValueError:\n",
    "            print(\"Error: square root of a negative number\")\n",
    "            return None\n",
    "    \n",
    "    def logarithm(self, x, base):\n",
    "        try:\n",
    "            return math.log(x, base)\n",
    "        except ValueError:\n",
    "            print(\"Error: invalid logarithm arguments\")\n",
    "            return None\n",
    "    \n",
    "    def factorial(self, x):\n",
    "        if x < 0:\n",
    "            print(\"Error: factorial of a negative number\")\n",
    "            return None\n",
    "        elif x == 0:\n",
    "            return 1\n",
    "        else:\n",
    "            return x * self.factorial(x-1)\n",
    "    \n",
    "    def fibonacci(self, n):\n",
    "        if n < 0:\n",
    "            print(\"Error: fibonacci sequence index cannot be negative\")\n",
    "            return None\n",
    "        elif n == 0:\n",
    "            return 0\n",
    "        elif n == 1:\n",
    "            return 1\n",
    "        else:\n",
    "            return self.fibonacci(n-1) + self.fibonacci(n-2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7\n"
     ]
    }
   ],
   "source": [
    "calc = Calculator()\n",
    "\n",
    "print(calc.add(3, 4)) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[1;31mType:\u001b[0m        module\n",
       "\u001b[1;31mString form:\u001b[0m <module 'pandas' from 'C:\\\\Users\\\\vaalt\\\\Anaconda3\\\\lib\\\\site-packages\\\\pandas\\\\__init__.py'>\n",
       "\u001b[1;31mFile:\u001b[0m        c:\\users\\vaalt\\anaconda3\\lib\\site-packages\\pandas\\__init__.py\n",
       "\u001b[1;31mDocstring:\u001b[0m  \n",
       "pandas - a powerful data analysis and manipulation library for Python\n",
       "=====================================================================\n",
       "\n",
       "**pandas** is a Python package providing fast, flexible, and expressive data\n",
       "structures designed to make working with \"relational\" or \"labeled\" data both\n",
       "easy and intuitive. It aims to be the fundamental high-level building block for\n",
       "doing practical, **real world** data analysis in Python. Additionally, it has\n",
       "the broader goal of becoming **the most powerful and flexible open source data\n",
       "analysis / manipulation tool available in any language**. It is already well on\n",
       "its way toward this goal.\n",
       "\n",
       "Main Features\n",
       "-------------\n",
       "Here are just a few of the things that pandas does well:\n",
       "\n",
       "  - Easy handling of missing data in floating point as well as non-floating\n",
       "    point data.\n",
       "  - Size mutability: columns can be inserted and deleted from DataFrame and\n",
       "    higher dimensional objects\n",
       "  - Automatic and explicit data alignment: objects can be explicitly aligned\n",
       "    to a set of labels, or the user can simply ignore the labels and let\n",
       "    `Series`, `DataFrame`, etc. automatically align the data for you in\n",
       "    computations.\n",
       "  - Powerful, flexible group by functionality to perform split-apply-combine\n",
       "    operations on data sets, for both aggregating and transforming data.\n",
       "  - Make it easy to convert ragged, differently-indexed data in other Python\n",
       "    and NumPy data structures into DataFrame objects.\n",
       "  - Intelligent label-based slicing, fancy indexing, and subsetting of large\n",
       "    data sets.\n",
       "  - Intuitive merging and joining data sets.\n",
       "  - Flexible reshaping and pivoting of data sets.\n",
       "  - Hierarchical labeling of axes (possible to have multiple labels per tick).\n",
       "  - Robust IO tools for loading data from flat files (CSV and delimited),\n",
       "    Excel files, databases, and saving/loading data from the ultrafast HDF5\n",
       "    format.\n",
       "  - Time series-specific functionality: date range generation and frequency\n",
       "    conversion, moving window statistics, date shifting and lagging.\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "pd?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "class Calculator:\n",
    "    \"\"\"\n",
    "    A simple calculator that can perform various mathematical operations.\n",
    "    \n",
    "    Methods\n",
    "    -------\n",
    "    add(x, y):\n",
    "        Adds two numbers and returns the result.\n",
    "        \n",
    "    subtract(x, y):\n",
    "        Subtracts the second number from the first number and returns the result.\n",
    "        \n",
    "    multiply(x, y):\n",
    "        Multiplies two numbers and returns the result.\n",
    "        \n",
    "    divide(x, y):\n",
    "        Divides the first number by the second number and returns the result. If the second number is zero, returns None.\n",
    "        \n",
    "    power(x, y):\n",
    "        Raises the first number to the power of the second number and returns the result.\n",
    "        \n",
    "    square_root(x):\n",
    "        Calculates the square root of the number and returns the result. If the number is negative, returns None.\n",
    "        \n",
    "    logarithm(x, base):\n",
    "        Calculates the logarithm of the number with the given base and returns the result. If the number is negative or the base is invalid, returns None.\n",
    "        \n",
    "    factorial(x):\n",
    "        Calculates the factorial of the number and returns the result. If the number is negative, returns None.\n",
    "        \n",
    "    fibonacci(n):\n",
    "        Generates the n-th number in the Fibonacci sequence and returns the result. If n is negative, returns None.\n",
    "    \"\"\"\n",
    "\n",
    "    def add(self, x, y):\n",
    "        \"\"\"Add two numbers and return the result.\"\"\"\n",
    "        return x + y\n",
    "\n",
    "    def subtract(self, x, y):\n",
    "        \"\"\"Subtract the second number from the first number and return the result.\"\"\"\n",
    "        return x - y\n",
    "\n",
    "    def multiply(self, x, y):\n",
    "        \"\"\"Multiply two numbers and return the result.\"\"\"\n",
    "        return x * y\n",
    "\n",
    "    def divide(self, x, y):\n",
    "        \"\"\"\n",
    "        Divide the first number by the second number and return the result.\n",
    "        If the second number is zero, returns None.\n",
    "        \"\"\"\n",
    "        try:\n",
    "            return x / y\n",
    "        except ZeroDivisionError:\n",
    "            print(\"Error: division by zero\")\n",
    "            return None\n",
    "\n",
    "    def power(self, x, y):\n",
    "        \"\"\"Raise the first number to the power of the second number and return the result.\"\"\"\n",
    "        return x ** y\n",
    "\n",
    "    def square_root(self, x):\n",
    "        \"\"\"\n",
    "        Calculate the square root of the number and return the result.\n",
    "        If the number is negative, returns None.\n",
    "        \"\"\"\n",
    "        try:\n",
    "            return x ** 0.5\n",
    "        except ValueError:\n",
    "            print(\"Error: square root of a negative number\")\n",
    "            return None\n",
    "\n",
    "    def logarithm(self, x, base):\n",
    "        \"\"\"\n",
    "        Calculate the logarithm of the number with the given base and return the result.\n",
    "        If the number is negative or the base is invalid, returns None.\n",
    "        \"\"\"\n",
    "        try:\n",
    "            return math.log(x, base)\n",
    "        except ValueError:\n",
    "            print(\"Error: invalid logarithm arguments\")\n",
    "            return None\n",
    "\n",
    "    def factorial(self, x):\n",
    "        \"\"\"\n",
    "        Calculate the factorial of the number and return the result.\n",
    "        If the number is negative, returns None.\n",
    "        \"\"\"\n",
    "        if x < 0:\n",
    "            print(\"Error: factorial of a negative number\")\n",
    "            return None\n",
    "        elif x == 0:\n",
    "            return 1\n",
    "        else:\n",
    "            return x * self.factorial(x-1)\n",
    "\n",
    "    def fibonacci(self, n):\n",
    "        \"\"\"\n",
    "        Generate the n-th number in the Fibonacci sequence and return the result.\n",
    "        If n is negative, returns None.\n",
    "        \"\"\"\n",
    "        if n < 0:\n",
    "            print(\"Error: fibonacci sequence index cannot be negative\")\n",
    "            return None\n",
    "        elif n == 0:\n",
    "            return 0\n",
    "        elif n == 1:\n",
    "            return 1\n",
    "        else:\n",
    "            return self.fibonacci(n-1) + self.fibonacci(n-2)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "\u001b[1;31mInit signature:\u001b[0m \u001b[0mCalculator\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
       "\u001b[1;31mDocstring:\u001b[0m     \n",
       "A simple calculator that can perform various mathematical operations.\n",
       "\n",
       "Methods\n",
       "-------\n",
       "add(x, y):\n",
       "    Adds two numbers and returns the result.\n",
       "    \n",
       "subtract(x, y):\n",
       "    Subtracts the second number from the first number and returns the result.\n",
       "    \n",
       "multiply(x, y):\n",
       "    Multiplies two numbers and returns the result.\n",
       "    \n",
       "divide(x, y):\n",
       "    Divides the first number by the second number and returns the result. If the second number is zero, returns None.\n",
       "    \n",
       "power(x, y):\n",
       "    Raises the first number to the power of the second number and returns the result.\n",
       "    \n",
       "square_root(x):\n",
       "    Calculates the square root of the number and returns the result. If the number is negative, returns None.\n",
       "    \n",
       "logarithm(x, base):\n",
       "    Calculates the logarithm of the number with the given base and returns the result. If the number is negative or the base is invalid, returns None.\n",
       "    \n",
       "factorial(x):\n",
       "    Calculates the factorial of the number and returns the result. If the number is negative, returns None.\n",
       "    \n",
       "fibonacci(n):\n",
       "    Generates the n-th number in the Fibonacci sequence and returns the result. If n is negative, returns None.\n",
       "\u001b[1;31mType:\u001b[0m           type\n",
       "\u001b[1;31mSubclasses:\u001b[0m     \n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "Calculator?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Object `Calculator.square` not found.\n"
     ]
    }
   ],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "# Machine Learning Models interpretability"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following code is used to build an CNN for facial expression recognition, for then ask ChatGPT to interpret this code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting tensorflow\n",
      "  Downloading tensorflow-2.12.0-cp39-cp39-win_amd64.whl (1.9 kB)\n",
      "Collecting tensorflow-intel==2.12.0\n",
      "  Downloading tensorflow_intel-2.12.0-cp39-cp39-win_amd64.whl (272.8 MB)\n",
      "     -------------------------------------- 272.8/272.8 MB 1.2 MB/s eta 0:00:00\n",
      "Collecting google-pasta>=0.1.1\n",
      "  Downloading google_pasta-0.2.0-py3-none-any.whl (57 kB)\n",
      "     ---------------------------------------- 57.5/57.5 kB 1.5 MB/s eta 0:00:00\n",
      "Collecting flatbuffers>=2.0\n",
      "  Downloading flatbuffers-23.3.3-py2.py3-none-any.whl (26 kB)\n",
      "Collecting tensorflow-io-gcs-filesystem>=0.23.1\n",
      "  Downloading tensorflow_io_gcs_filesystem-0.31.0-cp39-cp39-win_amd64.whl (1.5 MB)\n",
      "     ---------------------------------------- 1.5/1.5 MB 11.8 MB/s eta 0:00:00\n",
      "Requirement already satisfied: h5py>=2.9.0 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tensorflow-intel==2.12.0->tensorflow) (3.7.0)\n",
      "Requirement already satisfied: protobuf!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<5.0.0dev,>=3.20.3 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tensorflow-intel==2.12.0->tensorflow) (3.20.3)\n",
      "Requirement already satisfied: setuptools in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tensorflow-intel==2.12.0->tensorflow) (63.4.1)\n",
      "Collecting numpy<1.24,>=1.22\n",
      "  Downloading numpy-1.23.5-cp39-cp39-win_amd64.whl (14.7 MB)\n",
      "     --------------------------------------- 14.7/14.7 MB 16.0 MB/s eta 0:00:00\n",
      "Requirement already satisfied: six>=1.12.0 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tensorflow-intel==2.12.0->tensorflow) (1.16.0)\n",
      "Collecting astunparse>=1.6.0\n",
      "  Downloading astunparse-1.6.3-py2.py3-none-any.whl (12 kB)\n",
      "Collecting gast<=0.4.0,>=0.2.1\n",
      "  Downloading gast-0.4.0-py3-none-any.whl (9.8 kB)\n",
      "Collecting absl-py>=1.0.0\n",
      "  Downloading absl_py-1.4.0-py3-none-any.whl (126 kB)\n",
      "     -------------------------------------- 126.5/126.5 kB 2.5 MB/s eta 0:00:00\n",
      "Collecting jax>=0.3.15\n",
      "  Downloading jax-0.4.6.tar.gz (1.2 MB)\n",
      "     ---------------------------------------- 1.2/1.2 MB 19.5 MB/s eta 0:00:00\n",
      "  Preparing metadata (setup.py): started\n",
      "  Preparing metadata (setup.py): finished with status 'done'\n",
      "Collecting tensorboard<2.13,>=2.12\n",
      "  Downloading tensorboard-2.12.0-py3-none-any.whl (5.6 MB)\n",
      "     ---------------------------------------- 5.6/5.6 MB 18.0 MB/s eta 0:00:00\n",
      "Requirement already satisfied: packaging in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tensorflow-intel==2.12.0->tensorflow) (21.3)\n",
      "Collecting termcolor>=1.1.0\n",
      "  Downloading termcolor-2.2.0-py3-none-any.whl (6.6 kB)\n",
      "Collecting grpcio<2.0,>=1.24.3\n",
      "  Downloading grpcio-1.51.3-cp39-cp39-win_amd64.whl (3.7 MB)\n",
      "     ---------------------------------------- 3.7/3.7 MB 15.9 MB/s eta 0:00:00\n",
      "Requirement already satisfied: wrapt<1.15,>=1.11.0 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tensorflow-intel==2.12.0->tensorflow) (1.14.1)\n",
      "Collecting tensorflow-estimator<2.13,>=2.12.0\n",
      "  Downloading tensorflow_estimator-2.12.0-py2.py3-none-any.whl (440 kB)\n",
      "     -------------------------------------- 440.7/440.7 kB 6.9 MB/s eta 0:00:00\n",
      "Collecting opt-einsum>=2.3.2\n",
      "  Downloading opt_einsum-3.3.0-py3-none-any.whl (65 kB)\n",
      "     ---------------------------------------- 65.5/65.5 kB ? eta 0:00:00\n",
      "Requirement already satisfied: typing-extensions>=3.6.6 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tensorflow-intel==2.12.0->tensorflow) (4.3.0)\n",
      "Collecting keras<2.13,>=2.12.0\n",
      "  Downloading keras-2.12.0-py2.py3-none-any.whl (1.7 MB)\n",
      "     ---------------------------------------- 1.7/1.7 MB 18.4 MB/s eta 0:00:00\n",
      "Collecting libclang>=13.0.0\n",
      "  Downloading libclang-16.0.0-py2.py3-none-win_amd64.whl (24.4 MB)\n",
      "     --------------------------------------- 24.4/24.4 MB 11.7 MB/s eta 0:00:00\n",
      "Requirement already satisfied: wheel<1.0,>=0.23.0 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from astunparse>=1.6.0->tensorflow-intel==2.12.0->tensorflow) (0.37.1)\n",
      "Requirement already satisfied: scipy>=1.5 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from jax>=0.3.15->tensorflow-intel==2.12.0->tensorflow) (1.9.1)\n",
      "Collecting google-auth-oauthlib<0.5,>=0.4.1\n",
      "  Downloading google_auth_oauthlib-0.4.6-py2.py3-none-any.whl (18 kB)\n",
      "Requirement already satisfied: markdown>=2.6.8 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tensorboard<2.13,>=2.12->tensorflow-intel==2.12.0->tensorflow) (3.3.4)\n",
      "Collecting google-auth<3,>=1.6.3\n",
      "  Downloading google_auth-2.16.3-py2.py3-none-any.whl (177 kB)\n",
      "     ------------------------------------- 177.5/177.5 kB 10.5 MB/s eta 0:00:00\n",
      "Collecting tensorboard-data-server<0.8.0,>=0.7.0\n",
      "  Downloading tensorboard_data_server-0.7.0-py3-none-any.whl (2.4 kB)\n",
      "Requirement already satisfied: werkzeug>=1.0.1 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tensorboard<2.13,>=2.12->tensorflow-intel==2.12.0->tensorflow) (2.0.3)\n",
      "Collecting tensorboard-plugin-wit>=1.6.0\n",
      "  Downloading tensorboard_plugin_wit-1.8.1-py3-none-any.whl (781 kB)\n",
      "     -------------------------------------- 781.3/781.3 kB 9.9 MB/s eta 0:00:00\n",
      "Requirement already satisfied: requests<3,>=2.21.0 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from tensorboard<2.13,>=2.12->tensorflow-intel==2.12.0->tensorflow) (2.28.1)\n",
      "Requirement already satisfied: pyparsing!=3.0.5,>=2.0.2 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from packaging->tensorflow-intel==2.12.0->tensorflow) (3.0.9)\n",
      "Requirement already satisfied: cachetools<6.0,>=2.0.0 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from google-auth<3,>=1.6.3->tensorboard<2.13,>=2.12->tensorflow-intel==2.12.0->tensorflow) (5.3.0)\n",
      "Collecting rsa<5,>=3.1.4\n",
      "  Downloading rsa-4.9-py3-none-any.whl (34 kB)\n",
      "Requirement already satisfied: pyasn1-modules>=0.2.1 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from google-auth<3,>=1.6.3->tensorboard<2.13,>=2.12->tensorflow-intel==2.12.0->tensorflow) (0.2.8)\n",
      "Collecting requests-oauthlib>=0.7.0\n",
      "  Downloading requests_oauthlib-1.3.1-py2.py3-none-any.whl (23 kB)\n",
      "Requirement already satisfied: charset-normalizer<3,>=2 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from requests<3,>=2.21.0->tensorboard<2.13,>=2.12->tensorflow-intel==2.12.0->tensorflow) (2.0.4)\n",
      "Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from requests<3,>=2.21.0->tensorboard<2.13,>=2.12->tensorflow-intel==2.12.0->tensorflow) (1.26.11)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from requests<3,>=2.21.0->tensorboard<2.13,>=2.12->tensorflow-intel==2.12.0->tensorflow) (2022.9.14)\n",
      "Requirement already satisfied: idna<4,>=2.5 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from requests<3,>=2.21.0->tensorboard<2.13,>=2.12->tensorflow-intel==2.12.0->tensorflow) (3.3)\n",
      "Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in c:\\users\\vaalt\\anaconda3\\lib\\site-packages (from pyasn1-modules>=0.2.1->google-auth<3,>=1.6.3->tensorboard<2.13,>=2.12->tensorflow-intel==2.12.0->tensorflow) (0.4.8)\n",
      "Collecting oauthlib>=3.0.0\n",
      "  Downloading oauthlib-3.2.2-py3-none-any.whl (151 kB)\n",
      "     ---------------------------------------- 151.7/151.7 kB ? eta 0:00:00\n",
      "Building wheels for collected packages: jax\n",
      "  Building wheel for jax (setup.py): started\n",
      "  Building wheel for jax (setup.py): finished with status 'done'\n",
      "  Created wheel for jax: filename=jax-0.4.6-py3-none-any.whl size=1432714 sha256=015a5ac816b8a2f08915eb51db95c52ec075077d14d684210745c628b1090a89\n",
      "  Stored in directory: c:\\users\\vaalt\\appdata\\local\\pip\\cache\\wheels\\68\\2c\\93\\17deec4d117dc0675ed79e8e2af1e62fb1c41ed3955c540de0\n",
      "Successfully built jax\n",
      "Installing collected packages: tensorboard-plugin-wit, libclang, flatbuffers, termcolor, tensorflow-io-gcs-filesystem, tensorflow-estimator, tensorboard-data-server, rsa, oauthlib, numpy, keras, grpcio, google-pasta, gast, astunparse, absl-py, requests-oauthlib, opt-einsum, google-auth, jax, google-auth-oauthlib, tensorboard, tensorflow-intel, tensorflow\n",
      "  Attempting uninstall: numpy\n",
      "    Found existing installation: numpy 1.21.5\n",
      "    Uninstalling numpy-1.21.5:\n",
      "      Successfully uninstalled numpy-1.21.5\n",
      "Successfully installed absl-py-1.4.0 astunparse-1.6.3 flatbuffers-23.3.3 gast-0.4.0 google-auth-2.16.3 google-auth-oauthlib-0.4.6 google-pasta-0.2.0 grpcio-1.51.3 jax-0.4.6 keras-2.12.0 libclang-16.0.0 numpy-1.23.5 oauthlib-3.2.2 opt-einsum-3.3.0 requests-oauthlib-1.3.1 rsa-4.9 tensorboard-2.12.0 tensorboard-data-server-0.7.0 tensorboard-plugin-wit-1.8.1 tensorflow-2.12.0 tensorflow-estimator-2.12.0 tensorflow-intel-2.12.0 tensorflow-io-gcs-filesystem-0.31.0 termcolor-2.2.0\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n",
      "daal4py 2021.6.0 requires daal==2021.4.0, which is not installed.\n",
      "numba 0.55.1 requires numpy<1.22,>=1.18, but you have numpy 1.23.5 which is incompatible.\n"
     ]
    }
   ],
   "source": [
    "!pip install tensorflow"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf \n",
    "from tensorflow import keras \n",
    "import matplotlib.pyplot as plt \n",
    "import numpy as np "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\n",
      "170498071/170498071 [==============================] - 10s 0us/step\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "((50000, 32, 32, 3), (10000, 32, 32, 3), (50000, 1), (10000, 1))"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from keras.datasets import cifar10 \n",
    "#I'm dividing my data into train and test set \n",
    "(x_train, y_train), (x_test, y_test) = cifar10.load_data() \n",
    "x_train.shape, x_test.shape, y_train.shape, y_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "batch_size=32 \n",
    "epochs=1\n",
    "class_names = [\"airplane\",\"automobile\",\"bird\",\"cat\",\"deer\",\"dog\",\"frog\",\"horse\",\n",
    "\"ship\",\"truck\"] \n",
    "\n",
    "model=tf.keras.Sequential() \n",
    "model.add(tf.keras.layers.Conv2D(32,kernel_size=(3,3),activation='relu',input_shape=\n",
    "(32,32,1))) \n",
    "model.add(tf.keras.layers.MaxPooling2D(pool_size=(2,2))) \n",
    "model.add(tf.keras.layers.Flatten()) \n",
    "model.add(tf.keras.layers.Dense(1024,activation='relu')) \n",
    "model.add(tf.keras.layers.Dense(10,activation='softmax'))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING:absl:`lr` is deprecated in Keras optimizer, please use `learning_rate` or use the legacy optimizer, e.g.,tf.keras.optimizers.legacy.Adam.\n"
     ]
    }
   ],
   "source": [
    "model.compile(loss='categorical_crossentropy', optimizer=tf.keras.optimizers.Adam(lr=0.001), metrics=['accuracy']) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/3\n",
      "1563/1563 [==============================] - 208s 133ms/step - loss: 2.3021 - accuracy: 0.1038 - val_loss: 2.3029 - val_accuracy: 0.1039\n",
      "Epoch 2/3\n",
      "1563/1563 [==============================] - 209s 133ms/step - loss: 2.2964 - accuracy: 0.1104 - val_loss: 2.3070 - val_accuracy: 0.1001\n",
      "Epoch 3/3\n",
      "1563/1563 [==============================] - 909s 582ms/step - loss: 2.2743 - accuracy: 0.1312 - val_loss: 2.3173 - val_accuracy: 0.1006\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.History at 0x1cfcdfa5d00>"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.fit(np.resize(x_train, (50000,32,32,1))/255.0,\n",
    "        tf.keras.utils.to_categorical(y_train), \n",
    "        batch_size=batch_size, \n",
    "        shuffle=True, \n",
    "        epochs=epochs, \n",
    "        validation_data=(np.resize(x_test, (10000,32,32,1))/255.0,\n",
    "        tf.keras.utils.to_categorical(y_test)) \n",
    "        )\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true,
    "tags": []
   },
   "source": [
    "# Code translation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow import keras\n",
    "from tensorflow.keras import layers\n",
    "\n",
    "# Load the MNIST dataset\n",
    "(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()\n",
    "\n",
    "# Preprocess the data\n",
    "x_train = x_train.reshape(-1, 28*28) / 255.0\n",
    "x_test = x_test.reshape(-1, 28*28) / 255.0\n",
    "y_train = keras.utils.to_categorical(y_train)\n",
    "y_test = keras.utils.to_categorical(y_test)\n",
    "\n",
    "# Define the model architecture\n",
    "model = keras.Sequential([\n",
    "    layers.Dense(256, activation='relu', input_shape=(28*28,)),\n",
    "    layers.Dense(128, activation='relu'),\n",
    "    layers.Dense(10, activation='softmax')\n",
    "])\n",
    "\n",
    "# Compile the model\n",
    "model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n",
    "\n",
    "# Train the model\n",
    "history = model.fit(x_train, y_train, validation_split=0.2, epochs=10, batch_size=128)\n",
    "\n",
    "# Evaluate the model\n",
    "test_loss, test_acc = model.evaluate(x_test, y_test, verbose=0)\n",
    "print('Test accuracy:', test_acc)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "provenance": [],
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
